package service

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// 获取下单确认信息
func GetConfirmarFuOrder(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var returnData ConfirmarShopOrder
	//获取用户的下单地址
	var addressList []models.MMemberAddress
	err = models.DB.Model(new(models.MMemberAddress)).Where("mid=? AND aid=?", jsonData.Mid, jsonData.Aid).Find(&addressList).Error
	if err != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		return
	}
	//判断用户是否有收货地址
	if len(addressList) > 0 {
		cur := false
		//判断用户地址中是否有默认地址
		for _, v := range addressList {
			if v.Isdefault == 1 {
				returnData.Address = v
				cur = true
				break
			}
		}
		//如果没有默认地址，则选第一条地址
		if cur == false {
			returnData.Address = addressList[0]
		}
	}
	//获取商品信息
	var proData models.MFuProduct
	err = models.DB.Model(new(models.MFuProduct)).Where("id=?", jsonData.Id).First(&proData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		return
	}
	//获取用户信息
	var memberData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&memberData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		return
	}
	//获取用户等级信息
	var LevelData models.MMemberLevel
	err = models.DB.Model(new(models.MMemberLevel)).Where("id=?", memberData.Levelid).First(&LevelData).Error
	if err != nil {
		define.Response.ResultFail(c, 10004, define.JsonDataX, "")
		return
	}
	//获取系统设置
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", jsonData.Aid).First(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10005, define.JsonDataX, "")
		return
	}
	returnData.Name = adminData.Name
	returnData.Logo = adminData.Logo
	returnData.Juan = adminData.Juan
	returnData.JuanName = adminData.JuanName
	if proData.Scoredkmaxset == 0 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = adminData.Scoredkmaxval
	} else if proData.Scoredkmaxset == 1 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = proData.Scoredkmaxval
	} else if proData.Scoredkmaxset == 2 {
		returnData.Pro.Score2money = adminData.ScoreMoney
		returnData.Pro.Scoredkmaxpercent = proData.Scoredkmaxval
	} else if proData.Scoredkmaxset == -1 {
		returnData.Pro.Score2money = "0"
		returnData.Pro.Scoredkmaxpercent = decimal.NewFromFloat(0)
	}
	returnData.Pro.LeveldkMoney = LevelData.Discount
	returnData.Pro.Score = memberData.Score

	//获取服务区域信息
	newArr := strings.Split(proData.Freightdata, ",")
	for _, v := range newArr {
		var regionData models.MRegion
		num, _ := strconv.Atoi(v)
		err = models.DB.Model(new(models.MRegion)).Where("id=?", num).First(&regionData).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, define.JsonDataX, "")
			return
		}
		returnData.Region = append(returnData.Region, regionData)
	}
	//获取可用优惠券
	var couponData []models.MCouponRecord
	err = models.DB.Model(new(models.MCouponRecord)).Where("aid=? AND status=? AND mid=? AND type=?", jsonData.Aid, 0, jsonData.Mid, jsonData.Type).Find(&couponData).Error
	if err != nil {
		define.Response.ResultFail(c, 10007, define.JsonDataX, "")
		return
	}
	for _, v := range couponData {
		cur := false
		//是否是在使用的时间
		if time.Now().Unix() < int64(v.Usetime) {
			cur = true
		} else {
			continue
		}
		//判断商品是否可用
		var couData models.MCoupon
		err = models.DB.Model(new(models.MCoupon)).Where("id=?", v.Couponid).First(&couData).Error
		if err != nil {
			define.Response.ResultFail(c, 10007, define.JsonDataX, "")
			return
		}
		curFwtype := false
		if couData.Fwtype == 0 {
			curFwtype = true
		} else if couData.Fwtype == 1 { //判断栏目
			for _, m := range strings.Split(couData.Categoryids, ",") {
				n, _ := strconv.Atoi(m)
				if proData.CateId == n {
					curFwtype = true
					break
				}
				if proData.CateId2 == n {
					curFwtype = true
					break
				}
				if proData.CateId3 == n {
					curFwtype = true
					break
				}
				if proData.CateId4 == n {
					curFwtype = true
					break
				}
				if proData.CateId5 == n {
					curFwtype = true
					break
				}
				if proData.CateId6 == n {
					curFwtype = true
					break
				}
			}
		} else if couData.Fwtype == 2 { //判断商品
			for _, m := range strings.Split(couData.Productids, ",") {
				n, _ := strconv.Atoi(m)
				if n == proData.ID {
					curFwtype = true
					break
				}
			}
		}
		if curFwtype == true {
			cur = true
		} else {
			continue
		}
		//判断满足条件的优惠券
		if cur == true {
			returnData.CouponList = append(returnData.CouponList, v)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data":    returnData,
	})
}

type FuOrderjson struct {
	Aid          int             `json:"aid"`                                  //账户ID
	Mid          int             `json:"mid"`                                  //会员ID
	Proid        int             `gorm:"type:int(11);" json:"proid"`           //商品ID
	Name         string          `gorm:"type:varchar(255);" json:"name"`       //商品名称
	DPrice       decimal.Decimal `json:"d_price"`                              //商品单价
	Totalprice   decimal.Decimal `json:"totalprice"`                           //总金额
	ProductPrice decimal.Decimal `json:"product_price"`                        //商品金额
	ScoredkMoney decimal.Decimal `json:"scoredk_money"`                        //积分抵扣金额
	LeveldkMoney decimal.Decimal `json:"leveldk_money"`                        //会员等级优惠金额
	CouponMoney  decimal.Decimal `json:"coupon_money"`                         //优惠券金额
	CouponRid    string          `gorm:"type:varchar(255);" json:"coupon_rid"` //优惠券coupon_record的id
	Scoredkscore int             `gorm:"type:int(11);" json:"scoredkscore"`    //积分抵扣用掉的积分
	Ggid         int             `gorm:"type:int(11);"json:"ggid"`             //规格ID
	Message      string          `gorm:"type:varchar(255);" json:"message"`    //留言
	Paytypeid    int             `gorm:"type:int(11);" json:"paytypeid"`       //支付方式 2余额支付 1微信支付
	Paytype      string          `gorm:"type:varchar(255);" json:"paytype"`    //支付方式文本
	Platform     string          `gorm:"type:varchar(255);"json:"platform"`    //来源平台 mp公众号 wx微信小程序
	Num          int             `gorm:"type:int(11);" json:"num"`             //购买数量
	JuanPrice    decimal.Decimal `json:"juan_price"`                           //捐赠金额
}

// 创建订单服务订单
func AddFuOrder(c *gin.Context) {
	var jsonData FuOrderjson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	//获取系统设置
	var adminData models.MAdminSet
	err = models.DB.Model(new(models.MAdminSet)).Where("aid=?", jsonData.Aid).First(&adminData).Error
	if err != nil {
		define.Response.ResultFail(c, 10010, define.JsonDataX, "")
		return
	}
	//获取用户信息
	var memberData models.MMember
	err = models.DB.Model(new(models.MMember)).Where("id=?", jsonData.Mid).First(&memberData).Error
	if err != nil {
		define.Response.ResultFail(c, 10012, define.JsonDataX, "")
		return
	}
	//获取商品信息
	var proData models.MFuProduct
	err = models.DB.Model(new(models.MFuProduct)).Where("id=?", jsonData.Proid).First(&proData).Error
	if err != nil {
		define.Response.ResultFail(c, 10014, define.JsonDataX, "")
		return
	}
	//获取规格信息
	var GuigeData models.MShopGuigeFu
	err = models.DB.Model(new(models.MShopGuigeFu)).Where("id=?", jsonData.Ggid).First(&GuigeData).Error
	if err != nil {
		define.Response.ResultFail(c, 10013, define.JsonDataX, "")
		return
	}
	tx := models.DB.Begin() //开启事务
	//生成订单号
	Ordernum := strconv.FormatInt(time.Now().Unix(), 10) + define.RandomNum(4)
	//定义服务订单总表数据
	var OrderData models.MFuwuOrder
	OrderData.Aid = jsonData.Aid
	OrderData.Mid = jsonData.Mid
	OrderData.Ordernum = Ordernum
	OrderData.Proid = jsonData.Proid
	OrderData.Title = jsonData.Name
	OrderData.Totalprice = jsonData.Totalprice
	OrderData.ProductPrice = jsonData.ProductPrice
	OrderData.ScoredkMoney = jsonData.ScoredkMoney
	OrderData.LeveldkMoney = jsonData.LeveldkMoney
	OrderData.CouponMoney = jsonData.CouponMoney
	OrderData.CouponRid = jsonData.CouponRid
	OrderData.Scoredkscore = jsonData.Scoredkscore
	OrderData.Givescore = GuigeData.Givescore * jsonData.Num //单件规格积分*购买数量
	OrderData.Barcode = GuigeData.Barcode
	OrderData.Ggid = jsonData.Ggid
	OrderData.Ggname = GuigeData.Name
	OrderData.Createtime = int(time.Now().Unix())
	OrderData.Status = 0
	OrderData.Message = jsonData.Message
	OrderData.Paytypeid = jsonData.Paytypeid
	OrderData.Paytype = jsonData.Paytype
	OrderData.Platform = jsonData.Platform
	OrderData.UserDelete = 0
	OrderData.Num = jsonData.Num
	OrderData.JuanPrice = jsonData.JuanPrice
	//写入服务订单总表
	result := tx.Create(&OrderData)
	if result.Error != nil {
		define.Response.ResultFail(c, 10001, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//定义支付表数据
	var payOrderData models.MPayOrder
	payOrderData.Aid = jsonData.Aid
	payOrderData.Mid = jsonData.Mid
	payOrderData.Orderid = OrderData.ID
	payOrderData.Ordernum = Ordernum
	payOrderData.Type = 1
	payOrderData.Status = 0
	payOrderData.Bid = 0
	payOrderData.Createtime = int(time.Now().Unix())
	payOrderData.Money = jsonData.Totalprice
	payOrderData.Paytypeid = jsonData.Paytypeid
	payOrderData.Platform = jsonData.Platform
	payOrderData.Paytype = jsonData.Paytype
	payOrderData.Title = jsonData.Name
	err = tx.Create(&payOrderData).Error
	if err != nil {
		define.Response.ResultFail(c, 10002, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//给服务订单总表写入支付表id
	var editData = map[string]interface{}{
		"payorderid": payOrderData.Id,
	}
	err = tx.Model(new(models.MFuwuOrder)).Where("id=?", OrderData.ID).Updates(&editData).Error
	if err != nil {
		define.Response.ResultFail(c, 10003, define.JsonDataX, "")
		tx.Rollback()
		return
	}
	//定义服务套餐记录表数据
	for i := 0; i < jsonData.Num; i++ {
		//生成邀请码
		var inviteCode1 string
		for i := 0; i < 99; i++ {
			inviteCode1 = string(define.Krand(32, define.KC_RAND_KIND_ALL))
			var userList models.MFuwuOrderLog
			var inviteCode int64
			tx.Model(new(models.MFuwuOrderLog)).Where("hexiao_code=?", inviteCode1).Count(&inviteCode).Find(&userList)
			if inviteCode <= 0 {
				break
			}
		}
		var FuwuOrderLog models.MFuwuOrderLog
		FuwuOrderLog.Aid = jsonData.Aid
		FuwuOrderLog.Mid = jsonData.Mid
		FuwuOrderLog.Bid = 0
		FuwuOrderLog.Yid = 0
		FuwuOrderLog.Orderid = OrderData.ID
		FuwuOrderLog.Ordernum = Ordernum
		FuwuOrderLog.Proid = jsonData.Proid
		FuwuOrderLog.ProductPrice = jsonData.DPrice
		FuwuOrderLog.Barcode = GuigeData.Barcode
		FuwuOrderLog.Pic = proData.Pic
		FuwuOrderLog.Name = proData.Name
		FuwuOrderLog.Ggid = jsonData.Ggid
		FuwuOrderLog.Ggname = GuigeData.Name
		FuwuOrderLog.Createtime = int(time.Now().Unix())
		FuwuOrderLog.Status = 0
		FuwuOrderLog.HexiaoCode = inviteCode1
		FuwuOrderLog.IsZhuan = 0
		FuwuOrderLog.ZhuanId = strconv.Itoa(jsonData.Mid)
		err = tx.Create(&FuwuOrderLog).Error
		if err != nil {
			define.Response.ResultFail(c, 10004, define.JsonDataX, "")
			tx.Rollback()
			return
		}
		//查询服务明细
		var FuPro []models.MFuShopPro
		err = tx.Model(new(models.MFuShopPro)).Where("gid_fid=?", jsonData.Ggid).Find(&FuPro).Error
		//循环定义服务明细表数据
		var listData []models.MFuwuOrderGoods
		for _, v := range FuPro {
			Totalprice := int(define.IntDecimal(v.SellPrice)) * v.Num
			BusinessTotalMoney := int(define.IntDecimal(v.CostPrice)) * v.Num
			one := models.MFuwuOrderGoods{
				Aid:                jsonData.Aid,
				Mid:                jsonData.Mid,
				Tid:                FuwuOrderLog.ID,
				Proid:              jsonData.Proid,
				Orderid:            OrderData.ID,
				Ordernum:           Ordernum,
				Name:               v.Name,
				Num:                v.Num,
				YNum:               0,
				CostPrice:          v.CostPrice,
				SellPrice:          v.SellPrice,
				Totalprice:         decimal.NewFromInt(int64(Totalprice)),
				BusinessTotalMoney: decimal.NewFromInt(int64(BusinessTotalMoney)),
				Status:             0,
				Createtime:         int(time.Now().Unix()),
			}
			listData = append(listData, one)
		}
		//批量执行服务明细表数据
		err = tx.Model(new(models.MFuwuOrderGoods)).Create(&listData).Error
		if err != nil {
			define.Response.ResultFail(c, 10005, err.Error(), "")
			tx.Rollback()
			return
		}
	}
	if jsonData.Scoredkscore > 0 {
		//扣除用户的积分
		if memberData.Score < jsonData.Scoredkscore { //判断用户积分是否充足
			define.Response.ResultFail(c, 10006, define.JsonDataX, "")
			tx.Rollback()
			return
		}
		cur := models.ScoreEdit(tx, jsonData.Mid, jsonData.Scoredkscore, jsonData.Aid, memberData.Score, "购物积分抵扣，订单号:"+Ordernum)
		if cur == 2 {
			tx.Rollback()
			return
		}
	}
	//使用优惠券
	if jsonData.CouponRid != "" {
		arr := strings.Split(jsonData.CouponRid, ",")
		for _, m := range arr {
			curr, _ := strconv.Atoi(m)
			couSum := models.AddCoupon(tx, jsonData.Mid, jsonData.Aid, curr)
			if couSum == 2 {
				define.Response.ResultFail(c, 10007, define.JsonDataX, "")
				tx.Rollback()
				return
			}
		}
	}

	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"orderid":    OrderData.ID,
			"ordernum":   Ordernum,
			"payorderid": payOrderData.Id,
		},
	})
}
